<template>
  <div class="container">
    <h1 class="page-title">{{ title }}</h1>
    <div class="chat-container">
      <div class="chat-messages" ref="messagesContainer">
        <div
          v-for="(message, index) in messages"
          :key="index"
          :class="['message', message.isUser ? 'message-user' : 'message-ai']"
        >
          <div class="avatar" v-if="!message.isUser">
            <img src="../assets/ai-avatar.svg" alt="AI" @error="setDefaultAvatar($event, 'ai')">
          </div>
          <div
            class="message-content"
            v-if="!message.isUser"
            v-html="md.render(message.content)"
          ></div>
          <div
            class="message-content"
            v-else
          >{{ message.content }}</div>
          <div class="avatar" v-if="message.isUser">
            <img src="../assets/user-avatar.svg" alt="用户" @error="setDefaultAvatar($event, 'user')">
          </div>
        </div>
      </div>
      <div class="chat-input">
        <div class="input-container">
          <el-input
            v-model="inputMessage"
            class="input-box"
            placeholder="请输入您的问题..."
            @keyup.enter="sendMessage"
          ></el-input>
          <el-button type="primary" @click="sendMessage">发送</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, onUnmounted } from 'vue'
import { v4 as uuidv4 } from 'uuid'
import MarkdownIt from 'markdown-it'

const props = defineProps({
  title: {
    type: String,
    required: true
  },
  chatType: {
    type: String,
    required: true,
    validator: (value) => ['job-assistant', 'super-agent'].includes(value)
  }
})

const md = new MarkdownIt({
  html: false,
  linkify: true,
  breaks: true
})

// 状态
const messages = ref([])
const inputMessage = ref('')
const messagesContainer = ref(null)
const eventSource = ref(null)
const chatId = ref(uuidv4())

// 设置默认头像（如果图片加载失败）
const setDefaultAvatar = (event, type) => {
  if (type === 'ai') {
    event.target.src = ''
  } else {
    event.target.src = ''
  }
}

// 生命周期
onMounted(() => {
  // 显示欢迎消息
  const welcomeMessage = props.chatType === 'job-assistant' 
    ? '您好，我是AI求职小助手，请问有什么可以帮助您的？'
    : '您好，我是AI超级智能体，请问有什么可以帮助您的？'
  
  messages.value.push({
    content: welcomeMessage,
    isUser: false
  })
})

// 关闭SSE连接
const closeEventSource = () => {
  if (eventSource.value) {
    eventSource.value.close()
    eventSource.value = null
  }
}

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim()) return

  // 添加用户消息到列表
  messages.value.push({
    content: inputMessage.value,
    isUser: true
  })

  // 发送请求前，先关闭之前的连接
  closeEventSource()
  
  // 添加临时AI消息
  const aiMessageIndex = messages.value.length
  messages.value.push({
    content: '正在思考中...',
    isUser: false
  })

  try {
    // 根据不同类型调用不同API
    const { jobAssistantApi, superAgentApi } = await import('../services/api')
    
    if (props.chatType === 'job-assistant') {
      eventSource.value = jobAssistantApi.chatWithJobAssistant(inputMessage.value, chatId.value)
    } else {
      eventSource.value = superAgentApi.chatWithSuperAgent(inputMessage.value)
    }

    let responseText = ''

    eventSource.value.onmessage = (event) => {
      if (props.chatType === 'job-assistant') {
        responseText += event.data
        // 更新AI响应
        messages.value[aiMessageIndex] = {
          content: responseText,
          isUser: false
        }
      } else {
        // AI超级智能体：每个步骤单独一个气泡
        // 删除"正在思考中..."气泡（只保留一次）
        if (messages.value[aiMessageIndex] && messages.value[aiMessageIndex].content === '正在思考中...') {
          messages.value.splice(aiMessageIndex, 1)
        }
        messages.value.push({
          content: event.data,
          isUser: false
        })
      }
    }

    eventSource.value.onerror = (error) => {
      console.error('SSE Error:', error)
      closeEventSource()
      
      // 如果没有收到任何响应，更新错误信息
      if (!responseText) {
        messages.value[aiMessageIndex] = {
          content: '很抱歉，服务暂时不可用，请稍后再试。',
          isUser: false
        }
      }
    }
  } catch (error) {
    console.error('Chat Error:', error)
    // 显示错误信息
    messages.value[aiMessageIndex] = {
      content: '发生错误，请稍后再试。',
      isUser: false
    }
  }

  // 清空输入框
  inputMessage.value = ''
}

// 监听消息列表变化，自动滚动到底部
watch(messages, async () => {
  await nextTick()
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}, { deep: true })

// 组件销毁时关闭连接
onUnmounted(() => {
  closeEventSource()
})
</script>

<style scoped>
/* 修改聊天界面样式 */
.chat-container {
  height: 80vh;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  border: 1px solid rgba(65, 180, 255, 0.1);
  overflow: hidden;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #f9fafc;
  background-image: 
    linear-gradient(rgba(65, 180, 255, 0.03) 1px, transparent 1px), 
    linear-gradient(90deg, rgba(65, 180, 255, 0.03) 1px, transparent 1px);
  background-size: 20px 20px;
}

.message {
  margin-bottom: 20px;
  display: flex;
  align-items: flex-start;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.message-user {
  justify-content: flex-end;
}

.message-ai {
  justify-content: flex-start;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  margin: 0 10px;
  background-color: #f1f1f1;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.message-content {
  padding: 12px 16px;
  border-radius: 18px;
  max-width: 70%;
  word-break: break-word;
}

.message-user .message-content {
  background: linear-gradient(135deg, #7370ff, #41b4ff);
  color: white;
  border-top-right-radius: 4px;
}

.message-ai .message-content {
  background-color: white;
  color: #333;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border-top-left-radius: 4px;
}

.chat-input {
  padding: 15px;
  background: white;
  border-top: 1px solid #eaeaea;
}

.input-container {
  display: flex;
}

.input-box {
  flex: 1;
  margin-right: 10px;
}

.input-box :deep(.el-input__inner) {
  border-radius: 20px;
}

:deep(.el-button--primary) {
  background: linear-gradient(to right, #41b4ff, #7370ff);
  border: none;
  border-radius: 20px;
  font-weight: bold;
}

:deep(.el-button--primary:hover), :deep(.el-button--primary:focus) {
  background: linear-gradient(to right, #7370ff, #41b4ff);
  opacity: 0.9;
  border: none;
}
</style> 